package info.niwota.web.apache;

import info.niwota.web.Debug;
import info.niwota.web.Session;
import info.niwota.web.SessionManager;

import java.io.IOException;

import x.org.apache.http.Header;
import x.org.apache.http.HttpException;
import x.org.apache.http.HttpRequest;
import x.org.apache.http.HttpRequestInterceptor;
import x.org.apache.http.protocol.HttpContext;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class SessionRequestInterceptor implements HttpRequestInterceptor {

	private static final String TAG = "SessionRequestInterceptor";

	public SessionRequestInterceptor() {
	}

	public void process(HttpRequest request, HttpContext context)
			throws HttpException, IOException {
		//skip proxy request
		if (HttpUtils.isProxy(context)) {
			return;
		}
		
		// check sid
		Header[] cookies = HttpUtils.getCookies(request);
		final String sid = HttpUtils.scanSessionId(cookies);

		if (Debug.DEBUG) {
			Log.d(TAG, "process sid: " + sid);
		}
		
		Session session = SessionManager.get(sid, true);
		
		if (Debug.DEBUG) {
			Log.d(TAG, "attach session: " + session);
		}
		
		//
		request.removeHeaders(BaseHandler.SESSION_HEADER_KEY);
		request.addHeader(BaseHandler.SESSION_HEADER_KEY, session.id);
		
		context.setAttribute(SessionManager.SESSION_KEY, session);
	}
}
